import { Component, OnInit } from '@angular/core';
import { FadeInTop } from "../../shared/animations/fade-in-top.decorator";
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { JsonApiService } from "app/core/api/json-api.service";
import {config} from '../../shared/smartadmin.config';
import { NotificationService } from "../../shared/utils/notification.service";

declare var $: any;
declare var BMap: any;
declare var toWGS84: any;
declare var toMapPointArr: any;
declare var changeTime: any;

@FadeInTop()
@Component({
	selector: 'sa-car-station',
	templateUrl: './car-station.component.html',
})
export class CarStationComponent implements OnInit {
	
	myMap:any='';
	mapSize:any='';
	searchPointVal:any='';//搜索的经纬度
	positionMarker:any;//搜索的经纬度marker点
	pointIcon=new BMap.Icon("assets/img/trackImage/point.png", new BMap.Size(20, 50));
	
	stationlist:any=[];//站点列表数据数组
	stationMarkerlist:any=[];//站点对应marker数据数组
	
	activeIndex:any = false; //激活点击选中的站点
	isEditStatus=false;//是否处于编辑状态,true的时候不允许在百度地图上新标注,
	nowStation;//当前操作站点
	
	nowMarker;//当前站点的marker对象
	
//	判断停车点的条件和路线绘制变量
	stopSpeed=1.5; //全局变量，获取速度小于1.5的数据
	distanceLength=30;//全局变量，2点之间的距离，判断车辆是否停止的条件之一
	timeDistance=180000;//全局变量，单位毫秒，2点之间停止的事件，判断车辆是否停止的条件之一
	carTrackLine=[];//全局变量，绘画车辆路线数据对象
	carStopArr=[];//全局变量，车辆速度小于stopSpeed的数据对象
	
	deviceId:string = '';
	companyId:string = '';
	carNumber:string = '';
	createPointStatus='flase';//全局变量，控制是否可以点击地图添加覆盖物；当等于、true的时候可以，状态是添加站点的时候，flase是添加完成完成后不允许
	allPoint=[];//所有的点
	surePoint=[];//确认的点
	moveMarker={}//记录标记最后一个点;
	status='';//判定在多组的时候是否执行了删除操作；

	
	
	//街道表格部分
	tableData = []; //table数据
	selected = []; //row选择的数据
	temp = []; //数据缓存的地方
	totalCount = 0; //分页总条数
	curPage = 1; //分页当前页
	pageSize = 10; //内置的分页每页条数
	fixPageSize = 10; //扩展的pagesize控制
	searchKey = ''; //搜索keyword
	selectedRow = false;
	isShowTable=false;
	isAddStreet=false;
	
	//新建街道名
	addHouseNumber =1000;
	addStreetName='';
	addStreetTitle='新增';
	streetEditId=null;
	
	currentPage = 0;//缓存列表跳转过来的页码
	isPointer=false;
	
	constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService, private notificationService: NotificationService) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.deviceId  = queryParams.deviceId;
			this.companyId = queryParams.companyId;
			this.carNumber = queryParams.carNumber;
			this.currentPage = queryParams.nowPage;
		});
	}
	//返回车辆管理
	goBack(){
		this.router.navigate(['/system/car'],{ queryParams: {nowPage:this.currentPage}});
	}
	message(data){
		this.notificationService.smallBox({
	      content: data,
	      timeout: 1000
	    });
	}	
	
	confirm_message(message){
		 return new Promise(function (resolve, reject) {
 		    this.notificationService.smartMessageBox({
			      title: "提示",
			      content: message,
			      buttons: '[确认][取消]'
			    }, (ButtonPressed) => {
			    	if(ButtonPressed === "确认"){
			    		resolve();
			    	}
				    if (ButtonPressed === "取消") {
				        this.notificationService.smallBox({
				          content: "操作取消",
				          timeout: 3000
				        });
				        return ;
				    }
			
		    });
		 }.bind(this))
	}
	
	
	ngOnInit() {
		let  that=this;
		that.myMap=new BMap.Map("allmap",{enableMapClick: false});//我的地图
		that.myMap.centerAndZoom(new BMap.Point(113.46, 22.27), 10);  // 初始化地图,设置中心点坐标和地图级别
		that.myMap.addEventListener("zoomend", function(){   
			that.mapSize=this.getZoom();
		});
		
		that.myMap.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
		that.myMap.addEventListener("click",function(e){
			if(e.overlay){
				if(that.activeIndex){
					let isAppend=that.fillMustIsNull();
					if(!isAppend){
						return;
					}
				}
				let lng=e.overlay.point.lng;
				let lat=e.overlay.point.lat;
				let len=that.stationlist.length;
				for (let i=0;i<len;i++){
					let _len=that.stationlist[i].length;
					for(let j=0;j<_len;j++){
						let result=that.stationlist[i][j];
						let _lng=result.lng;
						let _lat=result.lat;
						result.marker.disableDragging();
						if(lng==_lng&&lat==_lat){
							that.isEditStatus=true;
							that.activeIndex=result.id;
							let marker=result.marker;
							that.myMap.closeInfoWindow(); 
							marker.enableDragging();
							marker.addEventListener("dragend", function(e){
								that.stationlist[i][j].lng=e.point.lng;
								that.stationlist[i][j].lat=e.point.lat;
							})
							
						}
					}
				}

			}	
			else{
				
				if(!that.activeIndex || that.isEditStatus){
					return;
				}
				if(that.nowMarker){
					that.myMap.removeOverlay(that.nowMarker);
				}
				let point=e.point;
				let marker=new BMap.Marker(point,{icon: that.pointIcon});
				marker.enableDragging();
				let len=that.stationlist.length;
				for (let i=0;i<len;i++){
					let x=that.stationlist[i].length;
					for (let j=0;j<x;j++){
						if(that.stationlist[i][j].id==that.activeIndex){
							that.stationlist[i][j].lng=e.point.lng;
							that.stationlist[i][j].lat=e.point.lat;
							that.stationlist[i][j].marker=marker;
							that.myMap.addOverlay(marker);
							that.nowMarker=marker;  // 当前站点标注
							marker.addEventListener("dragend", function(e){
								that.stationlist[i][j].lng=e.point.lng;
								that.stationlist[i][j].lat=e.point.lat;
				   				//marker.disableDragging();
				   			})
							marker.addEventListener("click",function(e){
								
								let isAppend=that.fillMustIsNull();
								if(!that.activeIndex){
									isAppend=that.fillMustIsNull();
								}
								if(!isAppend){
									return;
								}
								that.activeIndex=that.stationlist[i][j].id;
							})
							
						}
					}
				}
			}
		})
		that.initStationList();//初始化站点列表
		
		that.initSearch();//开启搜索匹配功能
		
		this.load();//初始化街道表单
		this.tableMove();//表单开启可拖动
		
		//导入插件插件js
		System.import('assets/js/timeControl.js');
		System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
			()=>{
				System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
					STATS.initTimeWidget();//初始化时间插件 
					STATS.iniParameter();//初始化时间参数
					
				});
			}
		);

		
	}
	
	//初始化所有站点
	initStationList () {
		
		this.myMap.clearOverlays();
		this.stationlist=[];
		let reqdata = 'deviceId=' + this.deviceId;
		this.jsonApiService.http('station/stationList.html',reqdata).subscribe(result=>{
			if(!result.success){
				this.message(result.message+',请添加站点');
			
			}
			let mapArr=toMapPointArr(result.data);
			let len=mapArr.length;
			
			if(len<1){
				
				let nullStation={'name': '',
						'houseNumber':'',
						'streetName': '', 
						'longitude': '',
						'lantitude':'',
						'deviceId':this.deviceId,
						'id':'null_'+0+0
					}
				let fristItem=[nullStation];
				
			
				this.stationlist.push(fristItem);
				
				this.activeIndex='null_'+0+0;
				
				
				
			}
			else{
				let max=mapArr[len-1].group+1;
				
				for (let _i=0;_i<max;_i++){
					let group=new Array();
					this.stationlist.push(group);
				}
				
				let groupLen=this.stationlist.length;

				
				for( let i = 0; i < len ; i++){
					
					let x=mapArr[i].group;
					for(let j=0; j<groupLen; j++){
						if(x==j){
						
							let point=new BMap.Point(mapArr[i].lng, mapArr[i].lat);
							let marker=new BMap.Marker(point,{icon: this.pointIcon});  // 创建标注
							this.myMap.addOverlay(marker);
							mapArr[i].marker=marker;
							let label = new BMap.Label(mapArr[i].name,{offset:new BMap.Size(-10,-15)});
							label.setStyle({
								color : "#2c40d7",
								border:'none',
								padding:'0'
							});
							marker.setLabel(label);
							
							this.stationlist[j].push(mapArr[i]);
						}
						
					}
					
				}
			}

			
			
		})
		
		
	}
	
	//查找出选定的点
	findStation(tiemId){
		
		if(this.activeIndex){
			let isAppend=this.fillMustIsNull();
			if(!isAppend){
				return;
			}
		}
		this.activeIndex = tiemId;
		this.isEditStatus=true;  
		let len=this.stationlist.length;
		for( let i = 0; i < len ; i++){
			let x=this.stationlist[i].length;
			for(let j=0; j<x; j++){
				this.stationlist[i][j].marker.disableDragging();
				let id=this.stationlist[i][j].id;
				if(tiemId==id){
					let result=this.stationlist[i][j]
					let content = "<div style='padding-top: 4px;'>站点名:" + result.name + "<br/>户籍数:" + result.houseNumber +
					"<br/>所在区域:" + result.streetName + "<br/>所在位置:" +common.twoDecimal(result.lng)+','+ common.twoDecimal(result.lat)+'</div>';
					let point = new BMap.Point(result.lng, result.lat);
					let infoWindow = new BMap.InfoWindow(content,{width: 200, heigth: 150,offset: new BMap.Size(0, -20)});  // 创建信息窗口对象 
					this.myMap.openInfoWindow(infoWindow,point); //开启信息窗口
					this.myMap.centerAndZoom(point, this.mapSize);
					if(!this.isPointer){
						this.isPointer=true;
						setTimeout(function() {
							$('.BMap_bottom').append('<div class="pointer"></div>');
						}, 100);
					}
					let marker=this.stationlist[i][j].marker;
					this.isEditStatus=true;
					marker.enableDragging();
					let that=this;
					marker.addEventListener("dragend", function(e){
						that.myMap.closeInfoWindow(); 
						that.stationlist[i][j].lng=e.point.lng;
						that.stationlist[i][j].lat=e.point.lat;
					})
				}
			}
		}
	}

	//阻止冒泡
	sotpEven(e){
		e.stopPropagation();
	}
	
	//判断站点的必要字段是否为空
	fillMustIsNull () {
		let notNull=true;
		let len=this.stationlist.length;
		for (let i=0;i<len;i++){
			let x=this.stationlist[i].length;
			for (let j=0;j<x;j++){
				let obj=this.stationlist[i][j];
				let name=obj.name;
				let lng=obj.lng;
				if(name==''||!lng||lng==''){
					notNull=false;
					this.message('请检查站点名称是否为空或未确定站点坐标');
				}
			}
		}
		return notNull;
	}
	
	
	//添加一个站点
	addStation(param){
		//添加站点时候判断是否有选中的当前站点
		let isAppend=this.fillMustIsNull();
	
		if(!isAppend){
			return;
		}
		this.isEditStatus=false;
		this.nowMarker=false;
		
		let len=this.stationlist[param].length;
		let sortId;
		if(len<1){
			sortId=0;
		}
		else{
			sortId=parseInt(this.stationlist[param][len-1].id.split('_')[1])+1;
		}
		
		let temObj = {
			'name': '',
			'houseNumber':'',
			'streetName': '', 
			'group':param,
			'index':len-1,
			'longitude': '',
			'lantitude':'',
			'deviceId':this.deviceId,
			'id':'null_'+param+sortId,
		};
		
		this.stationlist[param].push(temObj);
		this.activeIndex=temObj.id;
	}
	//删除一个站点
	deleteItem ($event,id) {
		$event.stopPropagation();
		
		this.confirm_message('此操作将永久删除数据,确认要删除?').then(()=>{
			
			this.activeIndex=id;
			let len=this.stationlist.length;
			for (let i=0;i<len;i++){
				let _len=this.stationlist[i].length;
				for(let j=0;j<_len;j++){
					let _id=this.stationlist[i][j].id;
					if(id==_id){
						let isSave=false;
						let x=_id.split('_').length;
						if(x<2){
							isSave=true
						}
						if(isSave){
							let  testArr=[];
							testArr.push(id);
							let testStr=JSON.stringify(testArr);
						    let reqdata="ids="+testStr;
							this.jsonApiService.http("station/deleteStation.html", reqdata).subscribe(result => {
								this.message(result.message);
							})
						}
						this.myMap.removeOverlay(this.stationlist[i][j].marker);
						this.stationlist[i].splice(j,1);  
						this.activeIndex = false; 
						break;
					}
				}
			}
		
		})	
		
	
	}
	
	//添加一组站点
	addGroup () {
		let isAppend=this.fillMustIsNull();
		if(!isAppend){
			return;
		}
		this.isEditStatus=false;
		this.nowMarker=false;
		let len = this.stationlist.length;
		let arr = [];
		let temObj = {
			'name': '',
			'houseNumber':'',
			'streetName': '', 
			'longitude': '',
			'lantitude':'',
			'id':'null_'+len+0,
			'group':len,
			'index':0,
			'deviceId':this.deviceId,
		};
		arr.push(temObj);
		
		this.stationlist.push(arr);
		this.activeIndex=temObj.id;
		
	}
	//删除一组站点
	deleteGroup(sort){
		this.confirm_message('此操作将永久删除这组数据,确认要删除?').then(()=>{
			let len=this.stationlist.length;
			for (let i=0;i<len;i++){
				if(sort==i){
					let _len=this.stationlist[i].length;
					let  delArr=[];
					for(let j=0;j<_len;j++){
						this.myMap.removeOverlay(this.stationlist[i][j].marker);
						let delId=this.stationlist[i][j].id;
						let x=delId.split('_').length;
						if(x<2){
							delArr.push(delId);
						}
						if(delArr.length>0){
							let delArrStr=JSON.stringify(delArr);
						    let reqdata="ids="+delArrStr;
							this.jsonApiService.http("station/deleteStation.html", reqdata).subscribe(result => {
								this.message(result.message);
							})
						}
					}
					this.stationlist.splice(i,1);
					this.activeIndex = false; 
					break;
				}
			}
		})	
	}
	//提交保存站点
	submitStation(){
		let isAppend=this.fillMustIsNull();
		if(!isAppend){
			return;
		}
		let arr=[];
		let len=this.stationlist.length;
		for (let i=0;i<len;i++){
			let _len=this.stationlist[i].length;
			for(let j=0;j<_len;j++){
				let wgs84=toWGS84(this.stationlist[i][j]);
				wgs84.longitude=wgs84.lng;
				wgs84.lantitude=wgs84.lat;
				arr.push(wgs84);
			}
		}
		for(let _x=0;_x<arr.length;_x++){
			let len=arr[_x].id.split('_').length;
			arr[_x].marker='';
			if(len>1){
				arr[_x].id=null;
			}
		}
	    let reqdata="list="+JSON.stringify(arr);
		this.jsonApiService.http("station/addStation.html", reqdata).subscribe(result => {
			this.message(result.message);
			this.activeIndex=false;
			this.initStationList();
		})
	}
	
	//绘画轨迹
	drawTrack () {
//		this.deviceId='431453255';
//		let	startTime='2018-05-10 00:00:33';
//		let endTime='2018-05-10 20:00:33';
		
		let startTime=$('#datetimepicker1').val();
		let endTime=$('#datetimepicker2').val();
		if(startTime.split(' ')[0]!==endTime.split(' ')[0]){
			this.message('只能查看同一天数据');
			return;
		}
		
		let reqdata = 'deviceId=' + this.deviceId + '&startTime=' + startTime + '&endTime=' + endTime;
		this.jsonApiService.http("track/localtrack.html", reqdata).subscribe(result => {
			if(result.success){
				let mapArr=toMapPointArr(result.data);
				let len=mapArr.length;
				let lineArr=[];
				let stopArr=[];
			
				for (let i =0;i<len;i++){
					lineArr.push(new BMap.Point(mapArr[i].lng,mapArr[i].lat));

					if(mapArr[i].speed<this.stopSpeed){
						let obj=mapArr[i];
						obj.loc_time=changeTime(mapArr[i].uploadDate),
        				stopArr.push(obj);
        			}
					
				}
				
				let point = new BMap.Point(mapArr[0].lng, mapArr[0].lat); //创建点坐标
				this.myMap.centerAndZoom(point, 12);
				var polyline = new BMap.Polyline(lineArr, {strokeColor:"#18a45b", strokeWeight:8, strokeOpacity:0.7,enableClicking: false}); 
				this.myMap.addOverlay(polyline);
				this.message('路线加载成功');
				this.stopMarker(stopArr);
			}
			else{
				this.message(result.message)
			}
			
		})
		
	}
	
	//停车点添加标注
	stopMarker (pointArr) {
		let stopPoint=[];
		let len=pointArr.length-1;
		for(let i=0;i<len;i++){
   			let point1=pointArr[i];
   			let point2=pointArr[i+1];
   			let distance=this.caculationDistance(point1,point2);
   			if(distance>this.distanceLength){
   				stopPoint.push(point1);
   			}
   		}
		
		if(stopPoint.length<1){
   			return;
   		}
		
		let stopLen=stopPoint.length;
		let stopTime=[];
		
		for(var  i=0;i<stopLen;i++){
   			var point=stopPoint[i];
   			var a=pointArr.indexOf(point);//取得每个停车点是在pointArr的第几个值取得的；
   			if(i<1){
   				stopTime.push(point.loc_time-pointArr[0].loc_time);
   			}
   			else{
   				var s=pointArr.indexOf(stopPoint[i-1]);//取得上个停车点在总数组中的排序
   				var y=pointArr[s+1];  //取得当前停车点开始进入停车状态的坐标；
   				var timeCha=point.loc_time-y.loc_time;
   				stopTime.push(timeCha);
   			}
   		}
		let that=this;
		let myIcon = new BMap.Icon('assets/img/trackImage/stop.png', new BMap.Size(20, 30));

		for(var i=0;i<stopTime.length;i++){
			if(stopTime[i]>this.timeDistance){

				let carPosition = new BMap.Point(stopPoint[i].lng, stopPoint[i].lat);
				let marker = new BMap.Marker(carPosition,{icon: myIcon});  // 创建标注
				let content = '<div style="text-align: center;">'+
	   				'<div><img src="assets/img/trackImage/stop2.png" style="width:10%;line-height:24px;position: absolute;left: 0; top: 24px;" /></div>'+
	   				'<div>载重量：'+stopPoint[i].weight+'（吨）</div>'+
	   				'<div style="line-height:48px">停车约：'+that.numberTotime(stopTime[i]);+'</div>'+
	   				'</div>';
				this.myMap.addOverlay(marker);
				this.addClickHandler(content,marker);
			}
			 
		 }
		
		
	}
	
	//监听标注点击事件
	addClickHandler (content,marker) {
		let that=this;
		marker.addEventListener("click",function(e){
			let point = new BMap.Point(marker.point.lng,marker.point.lat);
			let infoWindow = new BMap.InfoWindow(content,{width: 100, heigth: 150});  // 创建信息窗口对象 
			that.myMap.openInfoWindow(infoWindow,point); //开启信息窗口
			if(!that.isPointer){
				that.isPointer=true;
				setTimeout(function() {
					$('.BMap_bottom').append('<div class="pointer"></div>');
				}, 100);
			}
		});
		
		
	}
	
	//毫秒转换为时间
	numberTotime (data){
		let result=data/1000;
		let d=Math.floor(result/(3600*24));
		let h=Math.floor(result/3600%24);
		let m=Math.floor(result/60%60);
		let s=Math.floor(result%60);
		if(d<1){
			return h+'小时'+m+'分'+s+'秒';
		}
		else{
			return d+"天"+h+'小时'+m+'分'+s+'秒';
		}
	}
	
	caculationDistance(point1,point2) {
	   		let lng1=point1.lng;
	   		let lat1=point1.lat;
	
	
	   		let lat2=point2.lat;
	   		let lng2=point2.lng;
			let radius=6371393;//地球半径(米);
	     	let	radLat1 = lat1 * Math.PI / 180.0;
	      	let radLat2 = lat2 * Math.PI / 180.0;
	       	let a = radLat1 - radLat2;
	       	let b = (lng1 -lng2) * Math.PI / 180.0;
	       
	       	let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b/2),2)));
	       	s = s * radius;
		       
		    return s;
	    }
	
	
	//表格部分相关 start
	//  表格加载
	load() {
		let reqdata = 'gridPager={"pageSize":' + this.pageSize + ',"nowPage":' + this.curPage + ',"parameters":{"searchKey":"' + this.searchKey + '"}}'
		this.jsonApiService.http("station/streetpage.html", reqdata).subscribe(data => {
			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;
		})
	}
	
	
	//	表格搜索
	table_search(word) {
		this.load();
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	/**拖动list*/	
	tableMove(){
		$('body').delegate('.listTabel','mousedown',function(e){
			$(this).css("cursor","move");
		        
			var offset = $(this).position();
			
			var x = e.pageX - offset.left;
			var y = e.pageY - offset.top;
			$(document).bind("mousemove",function(ev){ 
				$(".listTabel").stop();
				
				var _x = ev.pageX - x;
				var _y = ev.pageY - y;
				$(".listTabel").animate({left:_x+"px",top:_y+"px"},2);  
		    });  
		});
	    $(document).mouseup(function(){  
            $(".listTabel").css("cursor","default");  
            $(this).unbind("mousemove");  
        }); 
		
	}
	
	//打开或关闭表格
	isTableOpen(param){
		if(param=='open'){
			this.isShowTable=true;
		}
		else{
			this.isShowTable=false;
		}
	}
	//打开或关闭添加街道模块
	isStreetAppend(param){
		if(param=='open'){
			this.addStreetTitle='新增';
			this.addStreetName='';
			this.addHouseNumber =1000;
			this.streetEditId=null;
			this.isAddStreet=true;
		}
		else{
			this.isAddStreet=false;
		}
	}
	
	//	表格修改街道
	editStreet(row){
		this.addStreetTitle='编辑';
		this.addStreetName=row.streetName;
		this.addHouseNumber =row.houseNumber;
		this.streetEditId=row.id;
		this.isAddStreet=true;
	}
	
	//提交添加/修改的区域信息
	submitStreet(){
		if(this.addStreetName==''){
			this.message('情输入区域名');
			return;
		}
		let editId=null;
		if(this.streetEditId){
			editId=this.streetEditId;
		}
		let reqdata ='id=' + this.streetEditId+'&companyId=' + this.companyId+'&deviceId='+this.deviceId+'&streetName='+this.addStreetName+'&houseNumber='+this.addHouseNumber;
		this.jsonApiService.http('station/addstreet.html',reqdata).subscribe(result=>{
			if(result.success){
				this.load();
				this.isAddStreet=false;
			}
			else{
				this.message(result.message);
			}
		})
		
	}
	
	refresh(){
		this.load();
	}
//	区域列表中的删除区信息
	removeStreet(row){
		
		this.confirm_message('此操作将永久删除数据,确认要删除?').then(()=>{
			let  delArr=[];
			delArr.push(row.id);
		    let reqdata="ids="+JSON.stringify(delArr);
			this.jsonApiService.http("station/delStreet.html", reqdata).subscribe(result => {
				this.message(result.message);
				this.load();
			})
		})
	}
	
	//	表格选中街道
	selectStreet(row){
		
		let len=this.stationlist.length;
		
		for( let i = 0; i < len ; i++){
						
			let x=this.stationlist[i].length;
			for(let j=0; j<x; j++){
				let id=this.stationlist[i][j].id;
				if(this.activeIndex==id){
					this.stationlist[i][j].houseNumber=row.houseNumber;
					this.stationlist[i][j].streetName=row.streetName;
				}
			}
		}
		
	}

	
//	表格部分相关 end
	
	
	
	initSearch () {
		let mp=this.myMap;
		let ac = new BMap.Autocomplete(    //建立一个自动完成的对象
			{"input" : "suggestId"
			,"location" : mp
		});
		ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
			let str = "";
			let _value = e.fromitem.value;
			let value = "";
			if (e.fromitem.index > -1) {
				value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
			}    
			str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
			
			value = "";
			if (e.toitem.index > -1) {
				_value = e.toitem.value;
				value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
			}    
			str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
			$("#searchResultPanel").text(str);
			
			
			let myValue;
			ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件和点击 
				let _value = e.item.value;
				myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
				$("#searchResultPanel").text("onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue);
				
				setPlace();
			});
			$('#search').click(function(){
				myValue=$('#suggestId').val();
		    	if(myValue!==''){
		    		setPlace();
		    	}
			});
			
			
			let setPlace=function (){
		
				let myFun=function (){
					let pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
					mp.centerAndZoom(pp, 18);
				}
			
			let local = new BMap.LocalSearch(mp, { //智能搜索
			  onSearchComplete: myFun
			});
			
			local.search(myValue);
			
		}
		});
		
	}
	
	//经纬度搜索
	searchPoint(){
		let val=this.searchPointVal.split(',');
		if(val==''){
			return;
		}
		if(this.positionMarker){
			this.myMap.removeOverlay(this.positionMarker)
		}
		let point={lng:val[0],lat:val[1]};
		this.positionMarker = new BMap.Marker(point);  // 创建标注
		this.myMap.addOverlay(this.positionMarker);              // 将标注添加到地图中
		this.myMap.centerAndZoom(new BMap.Point(point.lng, point.lat), 16);
	}
	
}